/**
 * 
 */
package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

/**
 * @author wudan_js
 *
 */
public class ClientNIODemo {
	public static void main(String[] args) {
		try {
			//创建客户端通道
			SocketChannel client=SocketChannel.open();
			Selector selector= Selector.open();
			//设置成非阻塞
			client.configureBlocking(false);
			client.connect(new InetSocketAddress("127.0.0.1", 12345));
			//注册监听Connect
			client.register(selector, SelectionKey.OP_CONNECT);
			boolean complate=true;
			while(complate){
				try {
					selector.select();
					System.out.println("==============select===========");
				} catch (IOException e) {
					e.printStackTrace();
					break;
				}
				Set<SelectionKey> keys= selector.selectedKeys();
				Iterator<SelectionKey> iterator = keys.iterator();
				
				while(iterator.hasNext()){
					SelectionKey key=iterator.next();
					iterator.remove();

					if(key.isConnectable()&&client.finishConnect()){
						System.out.println("=============connectable");
						key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
					}
					if(key.isReadable()){
						System.out.println("=============readable");
						SocketChannel channel=(SocketChannel) key.channel();
						ByteBuffer buffer=ByteBuffer.allocate(10);
						StringBuilder feedback=new StringBuilder();
						
						while(true){
							int res=channel.read(buffer);
							if(res==-1||res==0){
								break;
							}else if(res>0){
								buffer.flip();
								feedback.append(new String(buffer.array(),Charset.defaultCharset()));
								buffer.clear();
							}
						}
						
						System.out.println("[client]:"+feedback);
						complate=false;
					}
					if(key.isWritable()){
						System.out.println("=============writeable");
						SocketChannel channel=(SocketChannel) key.channel();
						ByteBuffer buffer=ByteBuffer.allocate(100);
						String message="send a message:客户端发消息了！";
						byte[] context=message.getBytes();
						buffer.put(context);
						buffer.flip();
						channel.write(buffer);
						key.interestOps(SelectionKey.OP_READ);
					}
				}
			}
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
}
